package main

import (
	"net/http"
	"strings"
	"global/libs/http/app"
	"github.com/ngaut/log"
	"global/model"
	"strconv"
)

// 搜索币种
func (h *Handler) OnHandleCoinSearchTag(writer http.ResponseWriter, request *http.Request) {
	tags, err := model.CoinSearchTagModel.FindAll()
	if err != nil {
		h.Error(app.ErrInnerError)
		return
	}

	data := make([]app.SearchTag, 0)
	for _, v := range tags {
		data = append(data, app.SearchTag{
			TagName: 	v.Keyword,
			Sort: 		v.Sort,
		})
	}

	response := app.AppMsg(data)
	h.Json(response)
}

// 搜索币种
func (h *Handler) OnHandleCoinSearch(writer http.ResponseWriter, request *http.Request) {
	keyword := strings.ToLower(request.FormValue("keyword"))
	uid, _ := strconv.Atoi(request.FormValue("uid"))
	if keyword == "" || uid < 0 {
		h.Error(app.ErrParameter)
		return
	}

	d, ErrorCode := h.getCoinSearchData(keyword, uid)
	if ErrorCode != app.ErrNone {
		h.Error(ErrorCode)
		return
	}

	response := app.AppMsg(d)
	h.Json(response)
}

// 获取搜索数据
func (h *Handler) getCoinSearchData(keyword string, uid int) ([]*app.SearchResult, app.AppErr) {
	// 获取搜索结果
	results, err := model.CoinModel.SearchByKeyWord(keyword)
	if err != nil {
		log.Errorf("Error: %s", err)
		return nil, app.ErrInnerError
	}

	likes, err := model.CoinLikeModel.SearchUserLikedCoins(uid)
	if err != nil {
		log.Errorf("Error: %s", err)
		return nil, app.ErrInnerError
	}

	userLikedCoins := make(map[string]bool, 0)
	for _, v := range likes {
		key := strings.ToUpper(v.CoinSymbol)
		userLikedCoins[key] = true
	}

	data := make([]*app.SearchResult, 0)
	for _, v := range results {
		var liked bool
		if _, ok := userLikedCoins[v.Symbol]; ok {
			liked = true
		}
		data = append(data, &app.SearchResult{
			Id: 		v.Id,
			NameCn: 	v.NameCn,
			NameEn: 	v.NameEn,
			Symbol: 	v.Symbol,
			Slug: 		v.Slug,
			Logo: 		v.Logo,
			Like: 		liked,
		})
	}
	return data, app.ErrNone
}

